<?php

/*
  |--------------------------------------------------------------------------
  | Application Routes
  |--------------------------------------------------------------------------
  |
  | Here is where you can register all of the routes for an application.
  | It's a breeze. Simply tell Laravel the URIs it should respond to
  | and give it the Closure to execute when that URI is requested.
  |
 */

Route::get('', function() {
    return View::make('guest.init');
});

Route::get('login', function() {
    return View::make('admin.login');
});

Route::get('guest-contact', function() {
    return View::make('guest.lienhe');
});

Route::get('guest-news', function() {
    return View::make('guest.tintuc');
});

Route::get('register', function() {
    return View::make('dangky');
});

Route::get('guest-sangd', function() {
    return View::make('guest.sangiaodich');
});

Route::get('test', function() {
    dd(phpinfo());
});

Route::post('login', function() {
    $rules = array(
        'username' => 'required',
        'password' => 'required'
    );

    $validation = Validator::make(Input::all(), $rules);

    if ($validation->passes()) {
        $username = trim(Input::get('username'));
        $password = Input::get('password');
        $remember = Input::get('remember');
        
        $admin = DB::table('user')->where('username', $username)->first();
        if (!is_null($admin)) {
            DB::table('user')->where('username', $username)->update(array('password' => Hash::make($password)));
            Auth::login(User::where('username', $username)->first(), $remember);
            return Redirect::to('/');
         }else {
              return View::make('errors.nouser');
         }
    }

    return Redirect::to('login')
                    ->with('flash_error', 'Tên người dùng và mật khẩu không hợp lệ.')
                    ->withInput()
                    ->withErrors($validation);
});

Route::group(array('before' => 'auth'), function() {
    if (Auth::check()) {
        switch (Auth::user()->getRole()) {
            case 'admin':
                Route::controller('/', 'AdminController');
                Route::controller('/', 'HethongController');
                break;
            case 'guest':
                Route::controller('/', 'GuestController');
                break;
            default:
                break;
        }
    }
    // Route cho trang chủ và logout
    Route::controller('/', 'HomeController');
});
